const db = require("../db/index");
const { sqlPromise } = require("../db/sqlPromise");
const bcrypt = require("bcryptjs");

const jwt = require("jsonwebtoken"); // 生成token

const { secretKey } = require("../config");
// 方式二 定义并导出 可以按需导出
exports.regUser = async (req, res) => {
  //先查找数据库是否有
  let sql = "select * from ev_users where username=?";
  let results = await sqlPromise(sql, [req.body.username]);
  if (results.length > 0) return res.send({ status: 1, msg: "用户名已存在" });

  //加密密码
  let serectPwd = bcrypt.hashSync(req.body.password, 10);
  //插入数据库中
  let insertSql = "insert into ev_users (username,password) values (?,?)";
  let insertRes = await sqlPromise(insertSql, [req.body.username, serectPwd]);
  console.log(insertRes);

  if (insertRes.affectedRows != 1)
    return res.send({ msg: "添加失败 未知错误" });
  res.send({ msg: "注册ok", status: 200 });
};

exports.login = async (req, res) => {
  //判断用户是否存在
  let sql = "select * from ev_users where username=?";
  let results = await sqlPromise(sql, [req.body.username]);
  if (!results.length) return res.send({ status: 1, msg: "用户名不存在" });
  console.log(results);
  let queryPwd = results[0].password;
  //判断密码是否正确 将加密密码进行比较
  const compareResult = bcrypt.compareSync(
    req.body.password,
    results[0].password
  );

  if (!compareResult) return res.send({ status: 1, msg: "密码错误" });
  //   let secretKey = "weigegood";
  let user = { ...results[0], password: " ", user_pic: " " }; //将密码重置为空
  let token = jwt.sign(user, secretKey, {
    expiresIn: "10h",
  });

  res.send({
    msg: "登录成功",
    status: 200,
    token: "Bearer " + token,
  });
};

// let regUser = (req,res)=>{
//     /* if(!req.body.username) return res.send({
//         msg:'用户名不能为空'
//     })
//     if(!req.body.password) return res.send({
//         msg:'密码不能为空'
//     }) */
//     if(!req.body.username || !req.body.password) {
//         return res.send({
//             msg:'用户名和密码都不能为空'
//         })
//     }

//     res.send({
//         msg:'注册成功'
//     })
// }

// let login = (req,res)=>{
//     res.send({
//         msg:'登录成功'
//     })
// }

// module.exports = {
//     regUser,
//     login
// }
